<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue 调用</title>
    <script type="text/javascript" src="../lib/include-lib.js" libpath="../lib/"
        include="jquery,bootstrap,bootstrap-checkbox,font-awesome,web-icons,layer,haoutil,nprogress,toastr,admui,turf,echarts-gl,redslib-wing"></script>
    <link href="./css/style.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>

<body>
    <div id="vueApp" style="width: 100%; height: 100%; background: grey; position: relative;">

        <div id="loadOverlay" class='loadingOverlay'>
            <ul id="loadbar" class="ins">
                <li>
                    <div id="loadinglayer1" class="ball"></div>
                    <div id="loadinglayer7" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer2" class="ball"></div>
                    <div id="loadinglayer8" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer3" class="ball"></div>
                    <div id="loadinglayer9" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer4" class="ball"></div>
                    <div id="loadinglayer10" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer5" class="ball"></div>
                    <div id="loadinglayer11" class="pulse"></div>
                </li>
            </ul>
        </div>
        <div id="mask" class="signmask"></div>


        <div id="centerDiv">
            <div id="redslibContainer" class="redslib-container" style="height:100%"></div>
        </div>

        <div style="position: absolute; color: aqua; top: 0; left: 0;"><button id="drawJson" onclick="drawEntityByJson()">json上图测试</button> </div>
    </div>
    <script type="text/javascript">
        Vue.createApp({
            data() {
                return {

                }
            }, beforeMount() {
                console.log("挂载前生命周期");
            },
            mounted() {
                console.log("挂载完成生命周期");
                initMap();
            }
        }).mount('#vueApp')
        function initMap() {
            var request = haoutil.system.getRequest();

            var configfile = "config.json";
            if (request.config)
                configfile = request.config;

            haoutil.loading.show();

            reds3d.createMap({
                id: 'redslibContainer',
                url: configfile + "?time=20231104",
                success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行
                    haoutil.loading.hide();
                    viewer = _viewer;
                    //初始化widget管理器
                    var hasAnimation = true;
                    if (haoutil.isutil.isNotNull(request.widget)) {
                        jsondata.widget.widgetsAtStart = [];
                        hasAnimation = false;
                    }
                    reds3d.widget.init(_viewer, jsondata.widget);

                    // 接受消息
                    window.addEventListener('message', e => {
                        if (e.data.type !== 'draw') return;

                        if(e.data.widgets == 'plot-api'){ //接收标绘组件发送的消息
                            console.log('标绘json:', e.data.data);
                            const data = e.data.data;
                            if (!data) return;

                            //测试：保存到本地
                            saveJSON(data, 'data.json')
                        }
                    })

                    setTimeout(function () {
                        $("#mask").remove();
                    }, 3000);
                    loaderOK();

                    //如果有xyz传参，进行定位
                    if (haoutil.isutil.isNotNull(request.x)
                        && haoutil.isutil.isNotNull(request.y)) {
                        viewer.wing.centerAt(request, { duration: 0, isWgs84: true });
                    }

                    function calback() {
                        //如果url传参，激活对应widget
                        if (haoutil.isutil.isNotNull(request.widget))
                            reds3d.widget.activate(request.widget);

                        initWork(_viewer);
                    }

                    if (hasAnimation) //开场动画
                        viewer.wing.openFlyAnimation(calback); //动画播放完成后执行calback回调
                    else {
                        calback();
                    }
                }
            });
        }
        function loaderOK() {
            $("#loadOverlay").hide();
            $('#loadbar').removeClass('ins');
            Window.LOADING_FLAG = true;
        }
        function initWork(viewer) {

            haoutil.oneMsg('如果未出现地球，是因为地形加载失败，请刷新重新加载！', 'terrain_tip');

            // 禁用默认的实体双击动作。
            viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
            viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_CLICK);

            //移动设备上禁掉以下几个选项，可以相对更加流畅
            if (!haoutil.system.isPCBroswer) {
                viewer.targetFrameRate = 20;        //限制帧率
                viewer.requestRenderMode = true;    //取消实时渲染
                viewer.scene.fog.enable = false;
                viewer.scene.skyAtmosphere.show = false;
                viewer.scene.fxaa = false;
            }

            //IE浏览器优化
            if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
                viewer.targetFrameRate = 20;        //限制帧率
                viewer.requestRenderMode = true;    //取消实时渲染
            }

            //更改配置，性能优化
            viewer.scene.logarithmicDepthBuffer = false;


            //设置操作习惯,更换中键和右键
            viewer.scene.screenSpaceCameraController.tiltEventTypes = [
                Redslib.CameraEventType.RIGHT_DRAG, Redslib.CameraEventType.PINCH,
                { eventType: Redslib.CameraEventType.LEFT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL },
                { eventType: Redslib.CameraEventType.RIGHT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL }
            ];
            viewer.scene.screenSpaceCameraController.zoomEventTypes = [Redslib.CameraEventType.MIDDLE_DRAG, Redslib.CameraEventType.WHEEL, Redslib.CameraEventType.PINCH];
        }

        //绑定图层管理
        function bindToLayerControl(options) {
            if (options._layer == null) {
                var _visible = options.visible;
                delete options.visible;

                var layer = new reds3d.layer.BaseLayer(options, viewer);
                layer._visible = _visible;
                options._layer = layer;
            }

            var manageLayersWidget = reds3d.widget.getClass('widgets/manageLayers/widget.js');
            if (manageLayersWidget) {
                manageLayersWidget.addOverlay(options);
            } else {
                viewer.gisdata.config.operationallayers.push(options);
            }
            return options._layer;
        }

        //取消绑定图层管理
        function unbindLayerControl(name) {
            var manageLayersWidget = reds3d.widget.getClass('widgets/manageLayers/widget.js');
            if (manageLayersWidget) {
                manageLayersWidget.removeLayer(name);
            } else {
                var operationallayersCfg = viewer.gisdata.config.operationallayers;
                for (var i = 0; i < operationallayersCfg.length; i++) {
                    var item = operationallayersCfg[i];
                    if (item.name == name) {
                        operationallayersCfg.splice(i, 1);
                        break;
                    }
                }
            }
        }

        //外部页面调用
        function activateWidget(item) {
            reds3d.widget.activate(item);
        }
        function disableWidget(item) {
            reds3d.widget.disable(item);
        }
        function activateFunByMenu(fun) {
            eval(fun);
        }

        //外部页面修改标绘
        function drawEntityByJson() {
          debugger
          debugger
            // 获取本地json
            $.ajax({
                type: "get",
                url:  "./test.json",
                async: false,
                success: function (results) {
                    var strjson = {
                      type:"draw",
                      widgets:"plot-api",
                      data: {
                      type:"FeatureCollection",
                        features:[{
                        type:"Feature",
                          properties:{
                            edittype:"polygon_clampToGround",
                            name:"贴地面",
                            position:{height:false, minCount:3},
                            style:{},
                            attr:{id:"20240109180955"},
                            type:"polygon"},
                                     geometry:
                                       {
                                         type:"Polygon",
                                         coordinates:[[[119.83057,31.235591,0], [119.833769,31.233616,0], [119.835255,31.236735,0], [119.833866,31.237322,0], [119.83057,31.235591,0]]]}
                      }]}}; //上图json
                    var isClearForOpenFile = true; //是否清除已上图的entity
                    var isFly = true; //上图后是否飞行到entity

                    var plotWidget = reds3d.widget.getClass('widgets/plot-api/widget.js');
                    plotWidget.create()
                    if (plotWidget) {
                        plotWidget.jsonToLayer(strjson, false, isFly)
                    }
                }
            });
        }

        function saveJSON(data, filename) {
            if (!data) {
                alert('data is null');
                index
                return;
            }
            if (!filename) filename = 'json.json'
            if (typeof data === 'object') {
                data = JSON.stringify(data, undefined, 4)
            }
            var blob = new Blob([data], {
                type: 'text/json'
            });
            var e = document.createEvent('MouseEvents');
            var a = document.createElement('a');
            a.download = filename;
            a.href = window.URL.createObjectURL(blob);
            a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
            e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
        }

    </script>
</body>

</html>
